// 战场逻辑和回合处理（重构版）
const axios = require('axios');
import bag_component from "../../component/bag_component";
import base_component from "../../component/base_component";
import rpg_component from "../../component/rpg_component";
import { Icard } from "../tool/Icard";
import { ComType } from "../tool/component";
import BuffManager from "./skill/BuffManager";
import { PassiveTriggerType, SkillType, TargetType } from "../../shared/face/enums";
import type { SkillData } from "./types";
import SkillManager from "./skill/SkManager";
import { TriggerConditionParser } from "./skill/TriggerConditionParser";
import { killLog } from "./types";
import { BaseBody } from "./entity/body_base";
import player from "./entity/player";
import follow_component from "../../component/follow_component";
import { Item } from "../../shared/face/index";
import BattleLogger from "./BattleLogger";
import sdk from '../index';
import { Bag } from "../bag";

// ==================== 类型定义 ====================

export interface BattleEndData {
  id: string;
  isWin: boolean;
  url: string;
  round: number;
  card: Icard;
  body: BaseBody;
}

interface PlayerStats {
  damage: number;
  damageTaken: number;
  healing: number;
}

interface BattleLogData {
  playerLogs: Map<string, string[]>;
  playerStats: Map<string, PlayerStats>;
  killLog: string[];
  logMap: Map<string, number>;
}

// ==================== 战场管理类 ====================

/**
 * 战场管理类 - 负责整个战斗流程的控制
 * 结构分区清晰，注释详细，方法职责单一
 */
export class BattleArea {
  // ==================== 核心属性 ====================
  
  // 战斗单位
  private homeUnits: rpg_component[] = [];
  private awayUnits: rpg_component[] = [];
  public round: number = 1;
  
  // 日志和统计
  public battleLog: BattleLogData = {
    playerLogs: new Map<string, string[]>(),
    playerStats: new Map<string, PlayerStats>(),
    killLog: [],
    logMap: new Map<string, number>()
  };
  
  // 奖励系统
  private rewardMap: Map<string, Bag> = new Map();
  
  // 回调函数
  private onKillCallback: (killLog: killLog, battleArea: BattleArea) => void = () => {};
  
  // 内部状态管理
  private playerMap: Map<string, boolean> = new Map();
  private triggerPassMap: Map<string, boolean> = new Map();

  constructor() {
    // 初始化战场
  }

  // ==================== 公共接口 ====================

  /**
   * 添加奖励到指定单位
   */
  addReward(unit: rpg_component, item: Item | Item[]): Bag {
    const unitId = unit.masterId || unit.id;
    let bag = this.rewardMap.get(unitId);
    
    if (!bag) {
      bag = new Bag();
      this.rewardMap.set(unitId, bag);
    }
    
    // 调试信息：记录添加的奖励
    if (Array.isArray(item)) {
      console.log(`添加奖励 - 单位ID: ${unitId}, 奖励数组长度: ${item.length}`);
      if (item.length === 0) {
        console.log(`警告: 奖励数组为空`);
      }
      item.forEach((singleItem, index) => {
        console.log(`奖励[${index}]: ${singleItem.name} x${singleItem.count} (${singleItem.type})`);
        bag!.addItem(singleItem);
      });
    } else {
      console.log(`添加奖励 - 单位ID: ${unitId}, 单个奖励: ${item.name} x${item.count} (${item.type})`);
      bag.addItem(item);
    }
    
    return bag;
  }

  /**
   * 添加单位到战场
   */
  addUnit(unity: BaseBody, isHome: boolean): void {
    const rpgComponent = unity.getComponent(ComType.rpg) as rpg_component;
    const unitsToAdd = this.collectUnitsFromBody(unity, rpgComponent);
    
    if (isHome) {
      this.addUnitsToTeam(unitsToAdd, this.homeUnits, this.awayUnits, isHome);
    } else {
      this.addUnitsToTeam(unitsToAdd, this.awayUnits, this.homeUnits, isHome);
    }
  }

  /**
   * 设置击杀回调
   */
  setOnKill(callback: (killLog: killLog, battleArea: BattleArea) => void): void {
    this.onKillCallback = callback;
  }

  /**
   * 记录击杀事件
   */
  logKill(killLogData: killLog): void {
    const baseCom = killLogData.unit.getComponent(ComType.base) as base_component;
    const baseComTarget = killLogData.target.getComponent(ComType.base) as base_component;
    
    const logKey = `${baseCom.id}-${baseComTarget.id}-${killLogData.skillName}-${killLogData.round}`;
    
    if (this.battleLog.logMap.has(logKey)) {
      debugger;
    }
    
    this.battleLog.logMap.set(logKey, 1);
    
    const killMessage = `${baseCom.nickName}在第${killLogData.round}回合使用${killLogData.skillName}击杀了${baseComTarget.nickName}`;
    
    if (this.battleLog.killLog.includes(killMessage)) {
      debugger;
    }
    
    this.battleLog.killLog.push(killMessage);
    this.onKillCallback(killLogData, this);
  }

  /**
   * 开始战斗
   */
  startBattle(endCallback: (data: BattleEndData) => void, dev: boolean = false): void {
    console.time('startBattle');
    
    // 启动战斗日志
    BattleLogger.startBattle(this.homeUnits, this.awayUnits);
    
    this.initializeBattle();
    this.executeBattleLoop();
    this.finalizeBattle(endCallback, dev);
    
    console.timeEnd('startBattle');
  }

  /**
   * 获取当前回合数
   */
  getRound(): number {
    return this.round;
  }

  /**
   * 获取玩家统计
   */
  getPlayerStats(): Map<string, PlayerStats> {
    return this.battleLog.playerStats;
  }

  /**
   * 获取玩家日志
   */
  getPlayerLogs(): Map<string, string[]> {
    return this.battleLog.playerLogs;
  }

  /**
   * 选择目标
   */
  selectTargets(unit: rpg_component, targetType: TargetType, allies?: rpg_component[], opponents?: rpg_component[]): rpg_component[] {
    if (!allies) {
      allies = unit._isHome ? this.homeUnits : this.awayUnits;
    }
    if (!opponents) {
      opponents = unit._isHome ? this.awayUnits : this.homeUnits;
    }

    // 去重
    allies = Array.from(new Set(allies));
    opponents = Array.from(new Set(opponents));

    switch (targetType) {
      case TargetType.我方不含自己:
        return allies.filter(target => !target.isDie() && target.id !== unit.id);
      case TargetType.我方:
        return allies.filter(target => !target.isDie());
      case TargetType.敌方:
        return opponents.filter(target => !target.isDie() && target.id !== unit.id);
      case TargetType.自己:
        return [unit];
      default:
        return [];
    }
  }

  // ==================== 私有方法 - 单位管理 ====================

  /**
   * 从身体对象收集所有单位（包括宠物）
   */
  private collectUnitsFromBody(unity: BaseBody, rpgComponent: rpg_component): rpg_component[] {
    const units = [rpgComponent];
    
    if (unity instanceof player) {
      this.playerMap.set(rpgComponent.id, true);
      const followComponent = unity.hasComponent(ComType.随从) as follow_component;
      
      if (followComponent) {
        for (const pet of followComponent._pets) {
          const petRpg = pet.getComponent(ComType.rpg) as rpg_component;
          units.push(petRpg);
        }
      }
    }
    
    return units;
  }

  /**
   * 将单位添加到指定队伍
   */
  private addUnitsToTeam(units: rpg_component[], teamUnits: rpg_component[], opponentUnits: rpg_component[], isHome: boolean): void {
    teamUnits.push(...units);
    
    for (const unit of units) {
      unit.battle_read(this, isHome);
      this.applyAuraEffectsForUnit(unit, teamUnits, opponentUnits);
    }
  }

  /**
   * 为单个单位应用光环效果
   */
  private applyAuraEffectsForUnit(unit: rpg_component, allies: rpg_component[], opponents: rpg_component[]): void {
    if (this.round === 1) return;
    
    unit.outSkills.forEach((skillData: SkillData) => {
      const skill = SkillManager.getSkillById(skillData.skillId);
      
      if (skill && skill.type === SkillType.光环技能) {
        skill.targetType.forEach((targetType, index) => {
          const targets = this.selectTargets(unit, targetType, allies, opponents);
          targets.forEach(target => {
            skill.effect(unit, target, skill, 1, index, {});
          });
        });
      }
    });
  }

  // ==================== 私有方法 - 战斗流程 ====================

  /**
   * 初始化战斗
   */
  private initializeBattle(): void {
    // 恢复所有单位生命值
    // this.restoreAllUnitsHealth();
    
    // 应用光环效果
    this.applyAuraEffects(this.homeUnits, this.awayUnits);
    this.applyAuraEffects(this.awayUnits, this.homeUnits);
  }

  /**
   * 测试方法 ---  恢复所有单位生命值
   */
  private restoreAllUnitsHealth(): void {
    const restoreHealth = (unit: rpg_component) => {
      unit.hp_now = unit.getAttribute('最大生命值');
      unit.clearShield(); // 清除护盾
    };
    
    this.homeUnits.forEach(restoreHealth);
    this.awayUnits.forEach(restoreHealth);
  }

  /**
   * 执行战斗循环
   */
  private executeBattleLoop(): void {
    while (!this.isBattleOver()) {
      this.startRound();
      this.endRound();
    }
  }

  /**
   * 结束战斗
   */
  private finalizeBattle(endCallback: (data: BattleEndData) => void, dev: boolean): void {
    // 移除光环效果
    this.removeAuraEffects(this.homeUnits, this.awayUnits);
    this.removeAuraEffects(this.awayUnits, this.homeUnits);
    
    // 结束战斗日志
    const homeWin = this.isBattleOver(true);
    const awayWin = this.isBattleOver(false);
    const winner = homeWin ? 'home' : awayWin ? 'away' : 'draw';
    BattleLogger.endBattle(winner, this.round);
    
    // 上传日志并回调（先生成结算卡片）
    this.uploadLog(dev).then((url) => {
      this.playerMap.forEach((isHome, id) => {
        const player = this.homeUnits.find(unit => unit.id === id) || 
                      this.awayUnits.find(unit => unit.id === id);
        
        if (!player) {
          debugger;
          return;
        }
        endCallback(this.getBattleEndData(url, isHome, player.getBody()));
      });
      // 结算奖励（回调后再执行）
      this.settlementReward();
    });
  }

  /**
   * 开始回合
   */
  startRound(): void {
    const aliveHomeUnits = this.homeUnits.filter(unit => !unit.isDie());
    const aliveAwayUnits = this.awayUnits.filter(unit => !unit.isDie());
    
    // 检查是否有一方全部死亡
    if (aliveHomeUnits.length === 0 || aliveAwayUnits.length === 0) {
      return;
    }
    
    // 主场单位行动
    aliveHomeUnits.forEach(unit => this.unitAction(unit, aliveAwayUnits, aliveHomeUnits));
    
    // 检查客场是否还有存活者
    const remainingAwayUnits = this.awayUnits.filter(unit => !unit.isDie());
    if (remainingAwayUnits.length === 0) {
      return;
    }
    
    // 客场单位行动
    remainingAwayUnits.forEach(unit => this.unitAction(unit, aliveHomeUnits, remainingAwayUnits));
    
    this.round++;
  }

  /**
   * 单位行动
   */
  unitAction(unit: rpg_component, opponents: rpg_component[], allies: rpg_component[]): void {
    const aliveOpponents = opponents.filter(opponent => !opponent.isDie());
    
    if (unit.isDie() || aliveOpponents.length === 0) {
      return;
    }
    
    // 选择目标
    const target = this.selectTargetForUnit(unit, aliveOpponents);
    if (!target || target.isDie()) {
      return;
    }
    
    // 执行攻击
    const skill = unit.attack([target, ...aliveOpponents], allies);
    if (!skill) {
      return;
    }
    
    // 触发被动技能
    this.triggerPassiveSkills(unit, allies, aliveOpponents, PassiveTriggerType.回合结束时);
  }

  /**
   * 为单位选择目标
   */
  private selectTargetForUnit(unit: rpg_component, opponents: rpg_component[]): rpg_component | null {
    let target = unit._currentTarget;
    
    if (!target || target.isDie()) {
      target = opponents[Math.floor(Math.random() * opponents.length)];
    }
    
    unit._currentTarget = target;
    return target;
  }

  /**
   * 结束回合
   */
  endRound(): void {
    this.triggerPassMap.clear();
    
    const processUnits = (units: rpg_component[]) => {
      units.filter(unit => !unit.isDie()).forEach(unit => {
        unit.reduceCooldowns();
        BuffManager.processBuffs(unit);
      });
    };
    
    processUnits(this.homeUnits);
    processUnits(this.awayUnits);
  }

  /**
   * 判断战斗是否结束
   */
  private isBattleOver(team?: boolean): boolean {
    if (typeof team === 'boolean') {
      const units = team ? this.awayUnits : this.homeUnits;
      return units.every(unit => unit.isDie());
    }
    
    return this.homeUnits.every(unit => unit.isDie()) || 
           this.awayUnits.every(unit => unit.isDie());
  }

  // ==================== 私有方法 - 光环效果 ====================

  /**
   * 应用光环效果
   */
  private applyAuraEffects(allies: rpg_component[], opponents: rpg_component[]): void {
    allies.forEach(unit => {
      if (unit.isDie()) return;
      
      unit.outSkills.forEach((skillData: SkillData) => {
        const skill = SkillManager.getSkillById(skillData.skillId);
        
        if (!skill || skill.type !== SkillType.光环技能) {
          return;
        }
        
        BattleLogger.log('info', '应用光环技能', { 
          unitId: unit.id,
          skillId: skill.id,
          skillName: skill.name,
          targetTypes: skill.targetType
        });
        
        const localTargets = new Map<TargetType, rpg_component[]>();
        
        skill.targetType.forEach((targetType, index) => {
          const targets = localTargets.get(targetType) || 
                         this.selectTargets(unit, targetType, allies, opponents);
          localTargets.set(targetType, targets);
          
          BattleLogger.log('info', '光环技能目标', { 
            unitId: unit.id,
            skillId: skill.id,
            skillName: skill.name,
            targetType,
            targetCount: targets.length,
            targetIds: targets.map(t => t.id)
          });
          
          targets.forEach(target => {
            BattleLogger.log('info', '执行光环效果', { 
              unitId: unit.id,
              skillId: skill.id,
              skillName: skill.name,
              targetId: target.id,
              index
            });
            
            // 执行技能效果
            skill.effect(unit, target, skill, 1, index, skill.data?.[index] || {});
            
            // 应用技能配置的buff
            const skillWithBuffs = skill as any; // 类型断言，因为Skill接口没有buffs字段，但实际数据中有
            if (skillWithBuffs.buffs && skillWithBuffs.buffs.length > 0) {
              skillWithBuffs.buffs.forEach((buffConfig: any) => {
                BattleLogger.log('info', '应用光环buff', { 
                  unitId: unit.id,
                  skillId: skill.id,
                  skillName: skill.name,
                  targetId: target.id,
                  buffId: buffConfig.id,
                  duration: buffConfig.duration
                });
                
                // 使用BuffManager应用buff配置
                const BuffManager = require('./skill/BuffManager').default;
                BuffManager.applyBuffConfig(target, buffConfig, unit, skill.data?.[index] || {});
              });
            }
          });
        });
      });
    });
  }

  /**
   * 移除光环效果
   */
  private removeAuraEffects(allies: rpg_component[], opponents: rpg_component[]): void {
    // 当前实现为空，保留接口以便后续扩展
  }

  // ==================== 私有方法 - 被动技能 ====================

  /**
   * 触发被动技能
   */
  triggerPassiveSkills(unit: rpg_component, allies: rpg_component[], opponents: rpg_component[], triggerType: PassiveTriggerType): void {
    // 去重
    allies = Array.from(new Set(allies));
    opponents = Array.from(new Set(opponents));
    
    if (unit.isDie()) {
      BattleLogger.log('info', '死亡无法触发被动', { unitId: unit.id });
      return;
    }
    
    BattleLogger.log('info', '检查被动技能触发', { 
      unitId: unit.id, 
      triggerType, 
      skillCount: unit.outSkills.length 
    });
    
    unit.outSkills.forEach(skillData => {
      BattleLogger.log('info', '检查技能', { skillId: skillData.skillId });
      
      const skill = SkillManager.getSkillById(skillData.skillId);
      
      if (!skill) {
        BattleLogger.log('error', '技能不存在', { 
          skillId: skillData.skillId, 
          unitId: unit.id,
          unitSkills: unit.outSkills.map(s => s.skillId)
        });
        return;
      }
      
      if (skill.type !== SkillType.被动技能) {
        return;
      }
      
      BattleLogger.log('info', '检查被动技能', { 
        skillId: skill.id, 
        skillName: skill.name, 
        skillTriggerType: skill.triggerType, 
        currentTriggerType: triggerType 
      });
      
      if (skill.triggerType && !skill.triggerType.includes(triggerType)) {
        BattleLogger.log('info', '触发类型不匹配', { 
          skillId: skill.id, 
          skillName: skill.name,
          unitId: unit.id,
          expectedTypes: skill.triggerType,
          actualType: triggerType 
        });
        return;
      }
      
      if (!skill.triggerConditionConfig) {
        BattleLogger.log('info', '没有配置触发条件', { 
          skillId: skill.id, 
          skillName: skill.name,
          unitId: unit.id 
        });
        return; // 没有配置触发条件，默认不触发
      }
      
      BattleLogger.log('info', '检查触发条件', { 
        skillId: skill.id, 
        skillName: skill.name, 
        config: skill.triggerConditionConfig 
      });
      
      const conditionResult = TriggerConditionParser.parseConditionConfig(
        skill.triggerConditionConfig, 
        unit, 
        allies, 
        opponents, 
        this.round
      );
      
      BattleLogger.log('info', '触发条件结果', { 
        skillId: skill.id, 
        skillName: skill.name, 
        result: conditionResult 
      });
      
      BattleLogger.logPassiveTrigger(
        unit, 
        skill.id, 
        skill.name, 
        triggerType, 
        conditionResult, 
        conditionResult, 
        conditionResult ? undefined : '触发条件不满足'
      );
      
      if (conditionResult) {
        BattleLogger.log('info', '执行被动技能', { 
          skillId: skill.id, 
          skillName: skill.name,
          unitId: unit.id 
        });
        this.executePassiveSkill(unit, skill, allies, opponents);
      }
    });
  }

  /**
   * 执行被动技能
   */
  private executePassiveSkill(unit: rpg_component, skill: any, allies: rpg_component[], opponents: rpg_component[]): void {
    if (skill.onceBattle && unit._usedSkills.includes(skill.id)) {
      return;
    }
    
    const localTargets = new Map<TargetType, rpg_component[]>();
    
    skill.targetType.forEach((targetType: TargetType, index: number) => {
      const range = skill.range?.[index] || 1;
      const effectTargets = localTargets.get(targetType) || 
                           this.selectTargets(unit, targetType, allies, opponents);
      localTargets.set(targetType, effectTargets);
      
      const activeTargets = effectTargets.slice(0, range);
      
              activeTargets.forEach(target => {
          if (target.isDie()) {
            BattleLogger.log('info', '对方死亡无法触发被动', { 
              targetId: target.id,
              skillId: skill.id,
              skillName: skill.name 
            });
            return;
          }
        
        const triggerKey = `${unit.id}-${target.id}-${skill.id}`;
        if (this.triggerPassMap.has(triggerKey)) {
          return;
        }
        
        this.triggerPassMap.set(triggerKey, true);
        skill.effect(unit, target, skill, 1, index, {});
        unit._usedSkills.push(skill.id);
      });
    });
  }

  // ==================== 私有方法 - 奖励系统 ====================

  /**
   * 结算奖励
   */
  private settlementReward(): void {
    this.rewardMap.forEach((bag, unitId) => {
      const unit = this.homeUnits.find(u => u.id === unitId) || 
                   this.awayUnits.find(u => u.id === unitId);
      
      if (!unit) {
        debugger;
        return;
      }
      
      const bagComponent = unit.getComponent(ComType.背包) as bag_component;
      bagComponent.addBag(bag);
    });
  }

  /**
   * 获取战斗结束数据
   */
  private getBattleEndData(url: string, isHome: boolean, unit: BaseBody): BattleEndData {
    const card = sdk.tool.card.create();
    const isWin = this.isBattleOver(isHome);
    const reward = this.rewardMap.get(unit.id) || new Bag();
    
    // 调试信息：检查奖励内容
    console.log(`战斗结束 - 单位ID: ${unit.id}, 奖励Map大小: ${this.rewardMap.size}, 奖励Bag大小: ${reward.items.size}`);
    if (reward.items.size > 0) {
      reward.items.forEach((item, key) => {
        console.log(`奖励物品: ${item.name} x${item.count} (${item.type})`);
      });
    } else {
      console.log(`警告: 奖励Bag为空，没有奖励物品`);
    }
    
    card.title(isWin ? '战斗胜利' : '战斗失败');
    card.l(`详细记录:${url}`);
    card.l(`战斗共计:${this.round}回合`);
    
    // 只有当奖励不为空时才合并
    if (reward.items.size > 0) {
      console.log(`合并奖励卡片 - 奖励数量: ${reward.items.size}`);
      card.merge(reward.getCard('🎁战斗奖励'));
    } else {
      console.log(`警告: 奖励Bag为空，不合并奖励卡片`);
    }
    
    return {
      id: unit.id,
      isWin: isWin,
      url: url,
      round: this.round,
      card: card,
      body: unit
    };
  }

  // ==================== 私有方法 - 日志系统 ====================

  /**
   * 上传战斗日志
   */
  async uploadLog(dev: boolean): Promise<string> {
    const md = this.generateBattleLog();
    
    if (dev) {
      console.log(md);
      BattleLogger.log('info', '开发模式 - 战斗日志', { logContent: md });
      return 'http://dew-bot.cn/test/';
    }
    
    return this.uploadToFlarum(md);
  }

  /**
   * 生成战斗日志
   */
  private generateBattleLog(): string {
    let md = '';
    
    // 主场战报
    md += this.generateTeamReport('主场', this.homeUnits);
    
    // 客场战报
    md += this.generateTeamReport('客场', this.awayUnits);
    
    // 战斗统计
    md += this.generateBattleStats();
    
    // 击杀统计
    md += this.generateKillStats();
    
    return md;
  }

  /**
   * 生成队伍战报
   */
  private generateTeamReport(teamName: string, units: rpg_component[]): string {
    let report = `## 📜${teamName}战报\n\n`;
    
    units.forEach(unit => {
      const baseCom = unit.getComponent(ComType.base) as base_component;
      const logs = this.battleLog.playerLogs.get(baseCom.nickName);
      
      if (!logs) return;
      
      const logString = logs.join('│▌');
      report += `🧙‍[${baseCom.nickName}](https://qm.qq.com/q/VEua3umPus)│▌${logString}`;
      
      if (unit.id !== units[units.length - 1].id) {
        report += '\n\n';
      }
    });
    report += '\n\n';
    
    return report;
  }

  /**
   * 生成战斗统计
   */
  private generateBattleStats(): string {
    let stats = '\n\n## 🔥🔥战斗统计🔥🔥\n\n';
    
    const homeStats = this.calculateTeamStats(this.homeUnits);
    const awayStats = this.calculateTeamStats(this.awayUnits);
    
    // 生成主场统计
    this.homeUnits.forEach(unit => {
      stats += this.generateUnitStats(unit, homeStats);
    });
    
    stats += `主场伤害:${homeStats.damage} 主场治疗:${homeStats.healing} 主场承受伤害:${homeStats.damageTaken}\n`;
    
    // 生成客场统计
    this.awayUnits.forEach(unit => {
      stats += this.generateUnitStats(unit, awayStats);
    });
    
    stats += `客场伤害:${awayStats.damage} 客场治疗:${awayStats.healing} 客场承受伤害:${awayStats.damageTaken}\n`;
    
    return stats;
  }

  /**
   * 计算队伍统计
   */
  private calculateTeamStats(units: rpg_component[]): PlayerStats {
    const stats: PlayerStats = { damage: 0, damageTaken: 0, healing: 0 };
    
    units.forEach(unit => {
      const baseCom = unit.getComponent(ComType.base) as base_component;
      const unitStats = this.battleLog.playerStats.get(baseCom.id) || stats;
      
      stats.damage += unitStats.damage;
      stats.damageTaken += unitStats.damageTaken;
      stats.healing += unitStats.healing;
    });
    
    return stats;
  }

  /**
   * 生成单位统计
   */
  private generateUnitStats(unit: rpg_component, teamStats: PlayerStats): string {
    const baseCom = unit.getComponent(ComType.base) as base_component;
    const stats = this.battleLog.playerStats.get(baseCom.id) || { damage: 0, damageTaken: 0, healing: 0 };
    
    let unitStats = `[${baseCom.nickName}](https://qm.qq.com/q/VEua3umPus)\n\n`;
    
    // 伤害进度条
    const damagePercent = teamStats.damage === 0 ? 0 : Math.floor((stats.damage / teamStats.damage) * 10);
    const damageBar = '🟦'.repeat(damagePercent) + '⬜'.repeat(10 - damagePercent);
    unitStats += `🗡️伤害: ${damageBar} ${stats.damage} (${teamStats.damage === 0 ? 0 : Math.floor((stats.damage / teamStats.damage) * 100)}%)\n\n`;
    
    // 承伤进度条
    const damageTakenPercent = teamStats.damageTaken === 0 ? 0 : Math.floor((stats.damageTaken / teamStats.damageTaken) * 10);
    const damageTakenBar = '🟥'.repeat(damageTakenPercent) + '⬜'.repeat(10 - damageTakenPercent);
    unitStats += `🛡️承伤: ${damageTakenBar} ${stats.damageTaken} (${teamStats.damageTaken === 0 ? 0 : Math.floor((stats.damageTaken / teamStats.damageTaken) * 100)}%)\n\n`;
    
    // 治疗进度条
    if (stats.healing) {
      const healingPercent = Math.floor((stats.healing / teamStats.healing) * 10);
      const healingBar = '🟥'.repeat(healingPercent) + '⬜'.repeat(10 - healingPercent);
      unitStats += `💖治疗: ${healingBar} ${stats.healing} (${Math.floor((stats.healing / teamStats.healing) * 100)}%)\n\n`;
    }
    
    unitStats += '\n';
    return unitStats;
  }

  /**
   * 生成击杀统计
   */
  private generateKillStats(): string {
    let killStats = '\n\n## 🔥🔥击杀统计🔥🔥\n\n';
    this.battleLog.killLog.forEach(log => killStats += `${log}\n`);
    return killStats;
  }

  /**
   * 上传到Flarum论坛
   */
  private async uploadToFlarum(md: string): Promise<string> {
    const flarumUrl = 'https://bbs.dew-bot.cn/api/discussions';
    const flarumToken = 'eZ5kK6QFeQNW27lMjGIf9HHGrPpxfpNs8cTx0lNm';
    
    const postData = {
      data: {
        type: 'discussions',
        attributes: {
          title: '战斗日志',
          content: md
        },
        relationships: {
          tags: {
            data: [{
              id: '2',
              type: 'tags'
            }]
          }
        }
      }
    };
    
    try {
      const response = await axios.post(flarumUrl, postData, {
        headers: {
          'Authorization': `Token ${flarumToken}`,
          'Content-Type': 'application/json'
        }
      });
      
      const url = `https://dew-bot.cn/test/${response.data.data.id}`;
      BattleLogger.log('info', 'Flarum 主题发布成功', { url });
      return url;
    } catch (error: any) {
      BattleLogger.log('error', 'Flarum 主题发布失败', { error: error?.toString() || '未知错误' });
      return '日志上传失败';
    }
  }
} 